<template>
  <a-tabs v-model:activeKey="tabKey" style="padding: 24px">
    <!-- 网站设置 -->
    <a-tab-pane key="1" tab="网站设置">
      <a-form
        ref="formRef"
        :model="formState"
        :label-col="{ span: 3 }"
        :wrapper-col="{ span: 21 }"
        style="width: 1000px; padding-top: 30px"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
      >
        <!-- Logo -->
        <a-form-item label="PC学员端Logo" name="system.logo" style="margin-bottom: 30px">
          <div class="d-flex">
            <a-image v-if="logo" :src="logo" :preview="false" :height="40" />
            <div class="d-flex ml-24">
              <UploadImageButton text="更换Logo" @selected="handleLogoSelected" />
            </div>
            <span class="helper-text ml-8">（推荐尺寸:240x80px，支持JPG、PNG）</span>
          </div>
        </a-form-item>

        <!-- PC端地址 -->
        <a-form-item label="PC学员端地址" name="system.pc_url" style="margin-bottom: 30px">
          <a-input v-model:value="formState['system.pc_url']" style="width: 274px" placeholder="请填写PC学员端地址" />
        </a-form-item>

        <!-- H5端地址 -->
        <a-form-item label="H5学员端地址" name="system.h5_url" style="margin-bottom: 30px">
          <a-input v-model:value="formState['system.h5_url']" style="width: 274px" placeholder="请填写H5学员端地址" />
        </a-form-item>

        <!-- 标题 -->
        <a-form-item label="学员端标题" name="system.name" style="margin-bottom: 30px">
          <a-input v-model:value="formState['system.name']" allow-clear style="width: 274px" placeholder="请填写学员端标题" />
        </a-form-item>

        <!-- 页脚 -->
        <a-form-item label="学员端页脚" name="system.pc_index_footer_msg" style="margin-bottom: 30px">
          <a-input v-model:value="formState['system.pc_index_footer_msg']" allow-clear style="width: 274px" placeholder="请填写学员端页脚" />
        </a-form-item>

        <!-- 保存按钮 -->
        <a-form-item :wrapper-col="{ offset: 3, span: 21 }" style="margin-bottom: 30px">
          <a-button type="primary" html-type="submit" :loading="loading">保存</a-button>
        </a-form-item>
      </a-form>
    </a-tab-pane>

    <!-- 播放设置 -->
    <a-tab-pane key="2" tab="播放设置">
      <a-form
        :model="formState"
        :label-col="{ span: 3 }"
        :wrapper-col="{ span: 21 }"
        style="width: 1000px; padding-top: 30px"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
      >
        <!-- 禁止拖动进度条 -->
        <a-form-item label="禁止拖动进度条" name="player.disabled_drag" style="margin-bottom: 30px">
          <a-switch v-model:checked="formState['player.disabled_drag']" @change="onDragChange" />
          <span class="helper-text ml-8">（打开后禁止学员在首次学习中拖动进度条，以防刷课）</span>
        </a-form-item>

        <!-- 播放器跑马灯 -->
        <a-form-item label="播放器跑马灯" name="player.is_enabled_bullet_secret" style="margin-bottom: 30px">
          <a-switch v-model:checked="formState['player.is_enabled_bullet_secret']" @change="onSwitchChange" />
          <span class="helper-text ml-8">（打开后播放器会随机出现跑马灯水印，以防录屏传播）</span>
        </a-form-item>

        <!-- 跑马灯内容 -->
        <a-form-item label="跑马灯内容" style="margin-bottom: 30px">
          <a-form-item name="player.bullet_secret_text" no-style>
            <a-input v-model:value="formState['player.bullet_secret_text']" style="width: 274px" allow-clear placeholder="自定义跑马灯内容" />
          </a-form-item>

          <a-form-item no-style>
            <div style="display:inline-block; margin-left:12px;">
              <a-checkbox-group v-model:value="bulletOptions" @change="onBulletOptionsChange">
                <a-checkbox value="name">姓名</a-checkbox>
                <a-checkbox value="email">邮箱</a-checkbox>
              </a-checkbox-group>
            </div>
          </a-form-item>
        </a-form-item>

        <!-- 跑马灯颜色 -->
        <a-form-item label="跑马灯颜色" name="player.bullet_secret_color" style="margin-bottom: 30px">
          <a-input
            v-model:value="formState['player.bullet_secret_color']"
            style="width: 120px"
            placeholder="#FFFFFF"
          />
          <span class="helper-text ml-8">请输入16进制颜色值，如 #FF0000</span>
        </a-form-item>

        <!-- 跑马灯不透明度 -->
        <a-form-item label="跑马灯不透明度" style="margin-bottom: 30px">
          <a-slider
            v-model:value="formState['player.bullet_secret_opacity']"
            :min="0"
            :max="100"
            :step="1"
            style="width: 274px"
          />
          <span class="ml-8">{{ formState['player.bullet_secret_opacity'] }}%</span>
        </a-form-item>

        <!-- 播放器封面 -->
        <a-form-item label="播放器封面" name="player.cover" style="margin-bottom: 30px">
          <div class="d-flex">
            <a-image
              v-if="formState['player.cover_url']"
              :src="formState['player.cover_url']"
              :preview="false"
              :height="60"
            />
            <div class="d-flex">
              <UploadImageButton text="更换封面" @selected="handleCoverSelected" />
            </div>
            <span class="helper-text ml-8">（推荐尺寸: 1920x1080px，支持JPG、PNG）</span>
          </div>
        </a-form-item>

        <!-- 保存按钮 -->
        <a-form-item :wrapper-col="{ offset: 3, span: 21 }" style="margin-bottom: 30px">
          <a-button type="primary" html-type="submit" :loading="loading">保存</a-button>
        </a-form-item>
      </a-form>
    </a-tab-pane>

    <a-tab-pane key="3" tab="学员设置">
      <a-form
        :model="formState"
        :label-col="{ span: 3 }"
        :wrapper-col="{ span: 21 }"
        style="width: 1000px; padding-top: 30px"
        @finish="onFinish"
      >
        <!-- 默认头像 -->
        <a-form-item label="学员默认头像" name="member.default_avatar">
          <div class="d-flex">
            <a-image :src="avatar" :height="60" />
            <div class="ml-24">
              <UploadImageButton
                text="更换头像"
                @selected="(url, id) => {
                  avatar = url
                  formState['member.default_avatar'] = id
                }"
              />
            </div>
            <div class="helper-text ml-8">（推荐尺寸:100x100px，支持JPG、PNG）</div>
          </div>
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 3, span: 21 }">
          <a-button type="primary" html-type="submit" :loading="loading">
            保存
          </a-button>
        </a-form-item>
      </a-form>
    </a-tab-pane>
    <a-tab-pane key="4" tab="S3存储">
      <a-form
        ref="formRef"
        :model="formState"
        :label-col="{ span: 3 }"
        :wrapper-col="{ span: 21 }"
        style="width: 1000px; padding-top: 30px"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
      >
        <!-- AccessKey -->
        <a-form-item label="AccessKey" name="s3.access_key" style="margin-bottom: 30px">
          <a-input
            v-model:value="formState['s3.access_key']"
            style="width: 274px"
            placeholder="请填写AccessKey"
            allow-clear
          />
        </a-form-item>

        <!-- SecretKey -->
        <a-form-item label="SecretKey" name="s3.secret_key" style="margin-bottom: 30px">
          <a-input-password
            v-model:value="formState['s3.secret_key']"
            style="width: 274px"
            placeholder="请填写SecretKey"
            allow-clear
          />
        </a-form-item>

        <!-- Bucket -->
        <a-form-item label="Bucket" name="s3.bucket" style="margin-bottom: 30px">
          <a-input
            v-model:value="formState['s3.bucket']"
            style="width: 274px"
            placeholder="请填写Bucket"
            allow-clear
          />
        </a-form-item>

        <!-- Region -->
        <a-form-item label="Region" name="s3.region" style="margin-bottom: 30px">
          <a-input
            v-model:value="formState['s3.region']"
            style="width: 274px"
            placeholder="请填写Region"
            allow-clear
          />
        </a-form-item>

        <!-- Endpoint -->
        <a-form-item label="Endpoint" name="s3.endpoint" style="margin-bottom: 30px">
          <a-input
            v-model:value="formState['s3.endpoint']"
            style="width: 274px"
            placeholder="请填写Endpoint"
            allow-clear
          />
        </a-form-item>

        <!-- 保存按钮 -->
        <a-form-item :wrapper-col="{ offset: 3, span: 21 }" style="margin-bottom: 30px">
          <a-button type="primary" html-type="submit" :loading="loading">保存</a-button>
        </a-form-item>
      </a-form>
    </a-tab-pane>
    <a-tab-pane key="5" tab="LDAP配置">
    <a-form
      :model="formState"
      :label-col="{ span: 3 }"
      :wrapper-col="{ span: 21 }"
      style="width: 1000px; padding-top: 30px"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <!-- 是否启用 -->
      <a-form-item label="启用" name="ldap.enabled" style="margin-bottom: 30px">
        <a-switch v-model:checked="formState['ldap.enabled']" @change="onLDAPChange" />
      </a-form-item>

      <!-- LDAP 地址 -->
      <a-form-item label="服务地址" name="ldap.url" style="margin-bottom: 30px">
        <a-input
          v-model:value="formState['ldap.url']"
          style="width: 274px"
          placeholder="请输入服务地址"
          allow-clear
        />
        <span class="helper-text ml-8">LDAP的对外服务地址。例如：ldap://ldap.example.com:389）</span>
      </a-form-item>

      <!-- 用户名 -->
      <a-form-item label="用户名" name="ldap.admin_user" style="margin-bottom: 30px">
        <a-input
          v-model:value="formState['ldap.admin_user']"
          style="width: 274px"
          placeholder="请填写用户名"
          allow-clear
        />
        <span class="helper-text ml-8">（用户登录到LDAP。例子：cn=admin,dc=playedu,dc=xyz）</span>
      </a-form-item>

      <!-- 密码 -->
      <a-form-item label="密码" name="ldap.admin_pass" style="margin-bottom: 30px">
        <a-input
          v-model:value="formState['ldap.admin_pass']"
          style="width: 274px"
          placeholder="请填写密码"
          allow-clear
        />
      </a-form-item>

      <!-- 密码 -->
      <a-form-item label="基本DN" name="ldap.base_dn" style="margin-bottom: 30px">
        <a-input
          v-model:value="formState['ldap.base_dn']"
          style="width: 274px"
          placeholder="请填写基本DN"
          allow-clear
        />
        <span class="helper-text ml-8">（从此节点搜索用户）</span>
      </a-form-item>

      <!-- 保存按钮 -->
      <a-form-item :wrapper-col="{ offset: 3, span: 21 }" style="margin-bottom: 30px">
        <a-button type="primary" html-type="submit" :loading="loading">保存</a-button>
      </a-form-item>
    </a-form>
  </a-tab-pane>
  </a-tabs>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { message } from "ant-design-vue";
import { appConfig, system } from "@/api/index";
import UploadImageButton from "@/components/Common/upload-image-button.vue";
import { useSystemStore } from "@/store";
import logoIcon from "@/assets/logo.png";
import memberDefaultAvatar from "@/assets/thumb/avatar.png"

const systemConfigStore = useSystemStore();

// 状态
const formRef = ref();
const formState = reactive<Record<string, any>>({
});
const loading = ref(false);
const tabKey = ref("1");

const logo = ref("");
const avatar = ref("");
const bulletOptions = ref<string[]>([]);

// 初始化
onMounted(() => {
  getDetail();
});

watch(tabKey, () => {
  getDetail();
});

// 获取详情
const getDetail = async () => {
  try {
    const res: any = await appConfig.appConfig();
    const configData = res.data.app_config || [];
    console.log('----------------------', configData)
    configData.forEach((item: any) => {
      formState[item.key_name] = item.key_value;
      if (item.key_name === "system.logo") {
        logo.value = item.key_value ? res.data.resource_url[Number(item.key_value)] : logoIcon;
      }
      if (item.key_name === "player.cover") {
        formState["player.cover_url"] = item.key_value ? res.data.resource_url[Number(item.key_value)] : "";
      }
      if (item.key_name === "member.default_avatar") {
        avatar.value = item.key_value ? res.data.resource_url[Number(item.key_value)] : memberDefaultAvatar;
      }
      if (item.key_name === "player.bullet_secret_text") {
        const val = item.key_value || "";
        const opts: string[] = [];
        if (val.includes("{name}")) opts.push("name");
        if (val.includes("{email}")) opts.push("email");
        bulletOptions.value = opts;
      }
      if (item.key_name === "player.bullet_secret_opacity" && item.key_value !== "") {
        formState["player.bullet_secret_opacity"] = Number(item.key_value) * 100;
      }
      if (item.key_name === "player.disabled_drag") {
        formState["player.disabled_drag"] = item.key_value === "1";
      }
      if (item.key_name === "player.is_enabled_bullet_secret") {
        formState["player.is_enabled_bullet_secret"] = item.key_value === "1";
      }
      if (item.key_name === "ldap.enabled") {
        formState["ldap.enabled"] = item.key_value === "1";
      }
    });
  } catch (err) {
    console.error("getDetail error", err);
  }
};

// checkbox 选中变化
const onBulletOptionsChange = (values: string[]) => {
  let base = formState["player.bullet_secret_text"] || "";
  base = base.replace("{name}", "").replace("{email}", "").replace("{idCard}", "");
  if (values.includes("name")) base += "{name}";
  if (values.includes("email")) base += "{email}";
  if (values.includes("idCard")) base += "{idCard}";
  formState["player.bullet_secret_text"] = base;
};

// 保存配置
const onFinish = async (values: any) => {
  if (loading.value) return;
  loading.value = true;

  values['player.disabled_drag'] = values['player.disabled_drag'] ? 1 : 0;
  values['player.is_enabled_bullet_secret'] = values['player.is_enabled_bullet_secret'] ? 1 : 0;
  values['ldap.enabled'] = values['ldap.enabled'] ? 1 : 0;

  if (typeof values["player.bullet_secret_opacity"] !== "undefined") {
    const v = values["player.bullet_secret_opacity"];
    values["player.bullet_secret_opacity"] = Array.isArray(v) ? v[0] / 100 : Number(v) / 100;
  }

  try {
    await appConfig.saveAppConfig(values);
    message.success("保存成功！");
    getDetail();
    await getSystemConfig();
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const onFinishFailed = (errorInfo: any) => {
  console.log("Failed:", errorInfo);
};

const getSystemConfig = async () => {
  try {
    const res: any = await system.getSystemConfig();
    systemConfigStore.setConfig({
      "ldap-enabled": res.data["ldap-enabled"],
      systemName: res.data["system.name"],
      systemLogo: res.data["system.logo"],
      systemPcUrl: res.data["system.pc_url"],
      systemH5Url: res.data["system.h5_url"],
      memberDefaultAvatar: res.data["member.default_avatar"],
      courseDefaultThumbs: res.data["default.course_thumbs"],
      departments: res.data["departments"],
      resourceCategories: res.data["resource_categories"],
      resourceUrl: res.data["resource_url"],
    });
  } catch (err) {
    console.error("getSystemConfig error", err);
  }
};

// logo 上传
const handleLogoSelected = (url: string, id: number) => {
  logo.value = url;
  formState["system.logo"] = id;
};

// 封面上传
const handleCoverSelected = (url: string, id: number) => {
  formState["player.cover"] = id;
  formState["player.cover_url"] = url;
};

// 开关事件
const onSwitchChange = (checked: boolean) => {
  formState["player.is_enabled_bullet_secret"] = checked;
};
const onDragChange = (checked: boolean) => {
  formState["player.disabled_drag"] = checked;
};
const onLDAPChange = (checked: boolean) => {
  formState["ldap.enabled"] = checked;
};
</script>

<style scoped>
.d-flex {
  display: flex;
  align-items: center;
}
.ml-8 {
  margin-left: 8px;
}
.ml-24 {
  margin-left: 24px;
}
.helper-text {
  color: #888;
  font-size: 13px;
}
</style>
